#include "RWGeometryTool.h"
#include <BRep_Builder.hxx>
#include <BRepBuilderAPI_MakeWire.hxx>
#include <TopoDS.hxx>
#include <BRepTools_WireExplorer.hxx>
#include <TopExp.hxx>
#include <TopoDS_Shell.hxx>
#include <TopExp_Explorer.hxx>
#include <ShapeAnalysis_FreeBounds.hxx>
#include <BRepBuilderAPI_MakeFace.hxx>
#include <BRepBuilderAPI_MakeSolid.hxx>
#include <gp_Pln.hxx>
#include <BRepAdaptor_Surface.hxx>
#include <BRepTools.hxx>
#include <BRepLib.hxx>
#include <BRepBuilderAPI_MakeEdge.hxx>
#include <ShapeAnalysis_Wire.hxx>
#include <BRepAlgoAPI_Common.hxx>
#include <Geom2d_Line.hxx>
#include <BRepOffsetAPI_MakePipe.hxx>
#include <GeomAPI_Interpolate.hxx>

bool RemoveEdgeFromWire(const TopoDS_Wire& originalWire, const TopoDS_Edge& edgeToRemove, TopoDS_Shape& remainingShape)
{
	BRep_Builder B;
	TopTools_ListOfShape remainingEdges;
	bool edgeFound = false;

	// 步骤1：按顺序收集所有Edge（跳过目标Edge）
	BRepTools_WireExplorer wireExp;
	for (wireExp.Init(originalWire); wireExp.More(); wireExp.Next()) {
		const TopoDS_Edge& currentEdge = wireExp.Current();
		if (currentEdge.IsSame(edgeToRemove)) {
			edgeFound = true;
			continue;
		}
		remainingEdges.Append(currentEdge);
	}

	// 异常处理：目标Edge不在Wire中
	if (!edgeFound) {
		remainingShape = originalWire;
		return false;
	}

	// 步骤2：创建Compound存放剩余部分
	TopoDS_Compound resultCompound;
	B.MakeCompound(resultCompound);

	// 步骤3：将剩余Edges分段处理（处理连续性中断）
	TopTools_ListOfShape currentSegment;
	TopoDS_Vertex lastVertex;  // 跟踪上一个Edge的终点

	for (auto it = remainingEdges.begin(); it != remainingEdges.end(); it++) {
		const TopoDS_Edge& edge = TopoDS::Edge(*it);
		TopoDS_Vertex startVtx, endVtx;
		TopExp::Vertices(edge, startVtx, endVtx);

		// 检查是否连续
		if (!lastVertex.IsNull() && !startVtx.IsSame(lastVertex)) {
			// 不连续时完成当前Segment
			if (!currentSegment.IsEmpty()) {
				AddSegmentToCompound(currentSegment, resultCompound);
				currentSegment.Clear();
			}
		}

		currentSegment.Append(edge);
		lastVertex = endVtx;  // 更新最后顶点
	}

	// 添加最后一个Segment
	if (!currentSegment.IsEmpty()) {
		AddSegmentToCompound(currentSegment, resultCompound);
	}

	remainingShape = resultCompound;

	return true;
}

void AddSegmentToCompound(const TopTools_ListOfShape& edges, TopoDS_Compound& compound)
{
	BRep_Builder B;
	BRepBuilderAPI_MakeWire wireMaker;

	for (auto it = edges.begin(); it != edges.end(); it++) {
		wireMaker.Add(TopoDS::Edge(*it));
	}

	if (wireMaker.IsDone()) {
		// 成功构建Wire
		B.Add(compound, wireMaker.Wire());
	}
	else {
		// 构建失败（不连续），单独添加Edge
		for (auto it = edges.begin(); it != edges.end(); it++) {
			B.Add(compound, *it);
		}
	}
}

TopoDS_Shape removeFaceFromShape(const TopoDS_Shape& solidShape, const TopoDS_Face& faceToRemove)
{
	// 1. 获取原始Solid的所有面
	TopTools_IndexedMapOfShape allFaces;
	TopExp::MapShapes(solidShape, TopAbs_FACE, allFaces);

	// 2. 创建新Shell的构建器
	BRep_Builder builder;
	TopoDS_Shell newShell;
	builder.MakeShell(newShell);

	// 3. 复制除目标面外的所有面到新Shell
	for (int i = 1; i <= allFaces.Extent(); i++) {
		TopoDS_Face currentFace = TopoDS::Face(allFaces(i));

		if (!currentFace.IsSame(faceToRemove)) {
			// 注意：需要复制几何体和方向信息
			builder.Add(newShell, currentFace);
		}
	}

	// 4. 关闭Shell（虽然现在已变成开放的）
	newShell.Free(Standard_True);

	return newShell;
}

bool hasMoreThanNumFace(const TopoDS_Shape& shape, int num)
{
	// 1. 创建面索引映射
	TopTools_IndexedMapOfShape faceMap;

	// 2. 提取形状中的所有面
	TopExp::MapShapes(shape, TopAbs_FACE, faceMap);

	// 3. 检查面数量是否大于1
	return (faceMap.Extent() >= num);
}

int GetSubShapeIndex(const TopoDS_Shape& shape, TopAbs_ShapeEnum type, const TopoDS_Shape& subShape)
{
	int i = 0;
	TopExp_Explorer explorer(shape, type);
	while (explorer.More())
	{
		if (subShape.IsEqual(explorer.Current()))
		{
			return i;
		}

		explorer.Next();
		i++;
	}

	return -1;
}

TopoDS_Shape GetSubShapeByIndex(const TopoDS_Shape& shape, TopAbs_ShapeEnum type, int index)
{
	int i = 0;
	for (TopExp_Explorer explorer(shape, type); explorer.More(); explorer.Next(), i++)
	{
		if (i == index)
		{
			return explorer.Current();
		}
	}

	return TopoDS_Shape();
}

TopoDS_Shape RemoveFaceAndKeepBoundary(const TopoDS_Shape& shape, const TopoDS_Face& faceToRemove)
{
	// 0. 验证输入有效性
	if (shape.IsNull() || faceToRemove.IsNull()) return shape;

	// 1. 提取被移除面的所有边界线（Wire）
	TopTools_ListOfShape boundaryWires;
	for (TopExp_Explorer wireExp(faceToRemove, TopAbs_WIRE); wireExp.More(); wireExp.Next()) {
		boundaryWires.Append(wireExp.Current());
	}

	// 2. 构建新容器：复制除指定面外的所有面
	BRep_Builder builder;
	TopTools_ListOfShape remainingFaces;
	TopTools_MapOfShape facesToRemove;
	facesToRemove.Add(faceToRemove);

	for (TopExp_Explorer faceExp(shape, TopAbs_FACE); faceExp.More(); faceExp.Next()) {
		const TopoDS_Shape& currentFace = faceExp.Current();
		if (!facesToRemove.Contains(currentFace)) {
			remainingFaces.Append(currentFace);
		}
	}

	// 3. 创建结果形状容器
	TopoDS_Compound result;
	builder.MakeCompound(result);

	// 4. 添加剩余面（如果有）
	if (!remainingFaces.IsEmpty()) {
		// 创建新壳体包含剩余面
		TopoDS_Shell newShell;
		builder.MakeShell(newShell);

		TopTools_ListIteratorOfListOfShape it(remainingFaces);
		for (; it.More(); it.Next()) {
			builder.Add(newShell, it.Value());
		}

		builder.Add(result, newShell);
	}

	// 5. 添加边界线（Wire）到结果
	TopTools_ListIteratorOfListOfShape wireIt(boundaryWires);
	for (; wireIt.More(); wireIt.Next()) {
		builder.Add(result, wireIt.Value());
	}

	return result;
}

TopoDS_Solid CloseOpenShellToSolid(const TopoDS_Shape& openShellShape)
{
	TopoDS_Shell openShell = ConvertToShell(openShellShape);

	// 1. 验证输入是否为 Shell
	if (openShell.IsNull())
	{
		std::cerr << "Error: The input shape is not a TopoDS_Shell." << std::endl;
		return TopoDS_Solid(); // 返回空的 Solid
	}

	// 2. 查找开放边界并构建线框 (Wire)
	// 使用 ShapeAnalysis_FreeBounds 是最高效、最可靠的方法
	// Standard_True 参数表示自动将找到的边界边连接成线框
	ShapeAnalysis_FreeBounds freeBounds(openShell, Standard_True);
	TopoDS_Compound closedWiresCompound = freeBounds.GetClosedWires();

	// 3. 从复合体中提取边界线框
	TopTools_ListOfShape wires;
	TopoDS_Iterator it(closedWiresCompound);
	while (it.More())
	{
		wires.Append(it.Value());
		it.Next();
	}

	// 检查是否只找到了一个边界线框，符合“只缺少一个面”的假设
	if (wires.Size() != 1)
	{
		std::cerr << "Error: Expected to find exactly one boundary wire, but found " << wires.Size() << "." << std::endl;
		std::cerr << "The shell might have multiple openings or is not open." << std::endl;
		return TopoDS_Solid();
	}

	TopoDS_Wire boundaryWire = TopoDS::Wire(wires.First());

	// 4. 根据边界线框创建新的面
	BRepBuilderAPI_MakeFace makeFace(boundaryWire);
	if (!makeFace.IsDone())
	{
		std::cerr << "Error: Failed to create the closing face from the boundary wire." << std::endl;
		return TopoDS_Solid();
	}
	TopoDS_Face closingFace = makeFace.Face();

	// 5. 将新创建的面与旧的开放壳组合成一个封闭的壳
	TopoDS_Shell closedShell = openShell; // 创建一个副本
	BRep_Builder builder;
	builder.Add(closedShell, closingFace);

	// 6. 使用封闭的壳创建实体
	BRepBuilderAPI_MakeSolid makeSolid(closedShell);
	if (!makeSolid.IsDone())
	{
		std::cerr << "Error: Failed to create a solid from the closed shell." << std::endl;
		return TopoDS_Solid();
	}

	TopoDS_Solid resultSolid = makeSolid.Solid();
	std::cout << "Successfully closed the open shell and created a solid." << std::endl;

	return resultSolid;
}

TopoDS_Shell ConvertToShell(const TopoDS_Shape& inputShape)
{
	if (inputShape.IsNull())
	{
		return TopoDS_Shell(); // 空输入返回空壳
	}

	// 根据形状类型进行分支处理
	switch (inputShape.ShapeType())
	{
		// Case 1: 输入本身就是 Shell
	case TopAbs_SHELL:
	{
		std::cout << "Input is already a Shell. Direct casting." << std::endl;
		return TopoDS::Shell(inputShape);
	}

	// Case 2: 输入是 Solid，提取其外壳
	case TopAbs_SOLID:
	{
		std::cout << "Input is a Solid. Exploring for shells within it." << std::endl;
		TopExp_Explorer shellExplorer(inputShape, TopAbs_SHELL);
		if (shellExplorer.More())
		{
			// 返回找到的第一个壳
			return TopoDS::Shell(shellExplorer.Current());
		}
		break; // 如果 Solid 内部没有 Shell（异常情况），则失败
	}

	// Case 3: 输入是 Compound，从中提取所有 Face 构建新 Shell
	case TopAbs_COMPOUND:
	{
		std::cout << "Input is a Compound. Extracting faces to build a new shell." << std::endl;
		BRep_Builder builder;
		TopoDS_Shell newShell;
		builder.MakeShell(newShell);

		TopExp_Explorer faceExplorer(inputShape, TopAbs_FACE);
		Standard_Boolean hasFaces = Standard_False;
		while (faceExplorer.More())
		{
			builder.Add(newShell, TopoDS::Face(faceExplorer.Current()));
			hasFaces = Standard_True;
			faceExplorer.Next();
		}

		if (hasFaces)
		{
			return newShell;
		}
		break; // 如果 Compound 中没有 Face，则失败
	}

	// Case 4: 输入是 Face，用它创建新 Shell
	case TopAbs_FACE:
	{
		std::cout << "Input is a Face. Creating a shell with this single face." << std::endl;
		BRep_Builder builder;
		TopoDS_Shell newShell;
		builder.MakeShell(newShell);
		builder.Add(newShell, inputShape);
		return newShell;
	}

	// Default: 其他不支持的类型
	default:
	{
		break;
	}
	}

	// 如果所有尝试都失败了
	std::cerr << "Warning: Could not convert the input shape of type "
		<< inputShape.ShapeType() << " to a TopoDS_Shell." << std::endl;
	return TopoDS_Shell(); // 返回一个 IsNull() 为 true 的空壳
}

TopoDS_Shape OffsetEdgeInPlanarShape(const TopoDS_Shape& aShape, const TopoDS_Edge& aEdge, const Standard_Real anOffsetDistance)
{
	// #TODO:未考虑move edge及其相邻edge为曲线
	// #Fix:对一个edge所在为一个face，不会填充

	// --- 第一步：查找宿主(Host)并验证其为唯一的平面几何体 ---
	TopoDS_Shape aHostShape;
	TopoDS_Wire aHostingWire;
	gp_Pln aPlane;
	bool hostFound = false;

	// 优先搜索面(Face)
	TopExp_Explorer faceExplorer(aShape, TopAbs_FACE);
	for (; faceExplorer.More(); faceExplorer.Next()) {
		const TopoDS_Face& currentFace = TopoDS::Face(faceExplorer.Current());
		TopExp_Explorer edgeExplorer(currentFace, TopAbs_EDGE);
		for (; edgeExplorer.More(); edgeExplorer.Next()) {
			if (edgeExplorer.Current().IsSame(aEdge)) {
				BRepAdaptor_Surface aSurfaceAdaptor(currentFace, Standard_True);
				if (aSurfaceAdaptor.GetType() != GeomAbs_Plane) {
					std::cout << "错误：边所在的面不是一个平面。" << std::endl;
					return TopoDS_Shape();
				}
				if (hostFound) {
					std::cout << "错误：边被多个子几何体共享。" << std::endl;
					return TopoDS_Shape();
				}
				aHostShape = currentFace;
				aHostingWire = BRepTools::OuterWire(currentFace);
				aPlane = aSurfaceAdaptor.Plane();
				hostFound = true;
				break;
			}
		}
		if (hostFound) break;
	}

	// 如果没找到面，则搜索线框(Wire)
	if (!hostFound) {
		TopExp_Explorer wireExplorer(aShape, TopAbs_WIRE);
		for (; wireExplorer.More(); wireExplorer.Next()) {
			const TopoDS_Wire& currentWire = TopoDS::Wire(wireExplorer.Current());
			TopExp_Explorer edgeExplorer(currentWire, TopAbs_EDGE);
			for (; edgeExplorer.More(); edgeExplorer.Next()) {
				if (edgeExplorer.Current().IsSame(aEdge)) {
					// ==================== 修正 #1 (最终版) 开始 ====================
					// 检查独立线框平面性的可靠方法：尝试从它构建一个面，并检查该面的几何类型。
					BRepBuilderAPI_MakeFace mf(currentWire);
					if (!mf.IsDone()) {
						std::cout << "错误：线框无法构成一个面（可能不闭合或自相交）。" << std::endl;
						return TopoDS_Shape();
					}
					TopoDS_Face tempFace = mf.Face();
					BRepAdaptor_Surface anAdaptor(tempFace, Standard_True);
					if (anAdaptor.GetType() != GeomAbs_Plane) {
						std::cout << "错误：边所在的线框不是平面的。" << std::endl;
						return TopoDS_Shape();
					}
					aPlane = anAdaptor.Plane();
					// ==================== 修正 #1 (最终版) 结束 ====================

					if (hostFound) {
						std::cout << "错误：边被多个子几何体共享。" << std::endl;
						return TopoDS_Shape();
					}
					aHostShape = currentWire;
					aHostingWire = currentWire;
					hostFound = true;
					break;
				}
			}
			if (hostFound) break;
		}
	}

	if (!hostFound || aHostingWire.IsNull()) {
		std::cout << "错误：在几何体中找不到指定的边或其宿主。" << std::endl;
		return TopoDS_Shape();
	}

	// --- 第二步：计算偏移向量 ---
	gp_Dir aNormal = aPlane.Axis().Direction();
	if (aHostShape.ShapeType() == TopAbs_FACE && aHostShape.Orientation() == TopAbs_REVERSED) {
		aNormal.Reverse();
	}
	Standard_Real u_first, u_last;
	Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aEdge, u_first, u_last);
	gp_Pnt aMidPoint;
	gp_Vec anEdgeTangent;
	aCurve->D1((u_first + u_last) / 2.0, aMidPoint, anEdgeTangent);
	anEdgeTangent.Normalize();
	if (aEdge.Orientation() == TopAbs_REVERSED) {
		anEdgeTangent.Reverse();
	}
	gp_Vec aOutwardDir = anEdgeTangent.Crossed(gp_Vec(aNormal));
	aOutwardDir.Normalize();
	gp_Vec aMoveVector = aOutwardDir * anOffsetDistance;

	// --- 第三步：获取有序边序列 ---
	TopTools_SequenceOfShape anOrderedEdges;
	if (aHostShape.ShapeType() == TopAbs_FACE) {
		ShapeAnalysis_Wire saw(aHostingWire, TopoDS::Face(aHostShape), 1.0e-5);
		// ==================== 修正 #2 (最终版) 开始 ====================
		// 必须通过 saw.WireData() 获取 ShapeExtend_WireData 句柄, 然后才能访问边。
		Handle(ShapeExtend_WireData) wd = saw.WireData();
		for (int i = 1; i <= wd->NbEdges(); ++i) {
			anOrderedEdges.Append(wd->Edge(i));
		}
		// ==================== 修正 #2 (最终版) 结束 ====================
	}
	else {
		BRepTools_WireExplorer anExp(aHostingWire);
		while (anExp.More()) {
			anOrderedEdges.Append(anExp.Current());
			anExp.Next();
		}
	}
	if (anOrderedEdges.IsEmpty()) {
		std::cout << "错误：未能成功获取有序边序列。" << std::endl;
		return TopoDS_Shape();
	}

	// --- 第四步：分析拓扑，移动顶点，创建新边 ---
	int nbEdges = anOrderedEdges.Length();
	int targetIdx = -1;
	for (int i = 1; i <= nbEdges; ++i) {
		if (anOrderedEdges.Value(i).IsSame(aEdge)) {
			targetIdx = i;
			break;
		}
	}
	if (targetIdx == -1) {
		std::cout << "错误：无法在有序线框中定位目标边。" << std::endl;
		return TopoDS_Shape();
	}

	const TopoDS_Edge& prevEdge = TopoDS::Edge(anOrderedEdges.Value((targetIdx == 1) ? nbEdges : targetIdx - 1));
	const TopoDS_Edge& nextEdge = TopoDS::Edge(anOrderedEdges.Value((targetIdx == nbEdges) ? 1 : targetIdx + 1));

	TopoDS_Vertex v1_target, v2_target;
	TopExp::Vertices(aEdge, v1_target, v2_target);

	auto findOtherVertex = [](const TopoDS_Edge& edge, const TopoDS_Vertex& vertex) -> TopoDS_Vertex {
		TopoDS_Vertex vA, vB;
		TopExp::Vertices(edge, vA, vB);
		return vA.IsSame(vertex) ? vB : vA;
		};
	TopoDS_Vertex v_prev_start = findOtherVertex(prevEdge, v1_target);
	TopoDS_Vertex v_next_end = findOtherVertex(nextEdge, v2_target);

	gp_Pnt p1_new = BRep_Tool::Pnt(v1_target).Translated(aMoveVector);
	gp_Pnt p2_new = BRep_Tool::Pnt(v2_target).Translated(aMoveVector);

	TopoDS_Edge newPrevEdge = BRepBuilderAPI_MakeEdge(BRep_Tool::Pnt(v_prev_start), p1_new);
	TopoDS_Edge newTargetEdge = BRepBuilderAPI_MakeEdge(p1_new, p2_new);
	TopoDS_Edge newNextEdge = BRepBuilderAPI_MakeEdge(p2_new, BRep_Tool::Pnt(v_next_end));

	// --- 第五步：重建几何体 ---
	anOrderedEdges.SetValue((targetIdx == 1) ? nbEdges : targetIdx - 1, newPrevEdge);
	anOrderedEdges.SetValue(targetIdx, newTargetEdge);
	anOrderedEdges.SetValue((targetIdx == nbEdges) ? 1 : targetIdx + 1, newNextEdge);

	BRepBuilderAPI_MakeWire newWireBuilder;
	for (const auto& edge : anOrderedEdges) {
		newWireBuilder.Add(TopoDS::Edge(edge));
	}

	if (!newWireBuilder.IsDone()) {
		std::cout << "错误：重建线框失败。" << std::endl;
		return TopoDS_Shape();
	}
	TopoDS_Wire newWire = newWireBuilder.Wire();

	TopoDS_Shape newSubShape = newWire;
	if (aHostShape.ShapeType() == TopAbs_FACE) {
		BRepBuilderAPI_MakeFace newFaceBuilder(aPlane, newWire);
		if (!newFaceBuilder.IsDone()) {
			std::cout << "错误：重建面失败。" << std::endl;
			return TopoDS_Shape();
		}
		newSubShape = newFaceBuilder.Face();
		newSubShape.Orientation(aHostShape.Orientation());
	}

	if (aShape.ShapeType() == TopAbs_COMPOUND) {
		TopoDS_Compound resultCompound;
		BRep_Builder builder;
		builder.MakeCompound(resultCompound);
		TopExp_Explorer finalExplorer(aShape, aHostShape.ShapeType());
		for (; finalExplorer.More(); finalExplorer.Next()) {
			if (finalExplorer.Current().IsSame(aHostShape)) {
				builder.Add(resultCompound, newSubShape);
			}
			else {
				builder.Add(resultCompound, finalExplorer.Current());
			}
		}
		return resultCompound;
	}
	else {
		return newSubShape;
	}
}

TopoDS_Shape CreateSectionFromSolid(const TopoDS_Shape& solidShape, const int& planeType)
{
	// 1. 判断输入是否为 Solid #TODO solid的形态有点多, 需要补充逻辑
	if (solidShape.IsNull() /*|| solidShape.ShapeType() != TopAbs_SOLID || solidShape.ShapeType() != TopAbs_COMPSOLID*/)
	{
		std::cerr << "Error: The input shape is not a valid solid." << std::endl;
		return TopoDS_Shape(); // 返回一个空的 Shape
	}

	// 2. 根据输入字符串创建几何平面 (gp_Pln)
	gp_Pln cuttingPlane;
	if (planeType == 0)
	{
		cuttingPlane = gp_Pln(gp::XOY()); // XY 平面 (z=0)
	}
	else if (planeType == 2)
	{
		cuttingPlane = gp_Pln(gp::YOZ()); // YZ 平面 (x=0)
	}
	else if (planeType == 1)
	{
		cuttingPlane = gp_Pln(gp::ZOX()); // XZ 平面 (y=0)
	}
	else
	{
		std::cerr << "Error: Invalid plane type specified. Use 'XY', 'YZ', or 'XZ'." << std::endl;
		return TopoDS_Shape();
	}

	// 3. 将几何平面转换为一个足够大的拓扑面 (TopoDS_Face)
	// 布尔运算需要两个拓扑形状。需要创建一个非常大的面来代表无限的平面。
	// 这里假设实体在 -1000 到 1000 的范围内。
	double half_dim = 1000.0;
	TopoDS_Face cuttingFace = BRepBuilderAPI_MakeFace(cuttingPlane, -half_dim, half_dim, -half_dim, half_dim);

	// 4. 执行布尔交集运算
	// BRepAlgoAPI_Common 用于计算两个形状的交集。
	BRepAlgoAPI_Common intersectionAlgorithm(solidShape, cuttingFace);
	intersectionAlgorithm.Build();

	// 5. 检查运算是否成功并返回结果
	if (!intersectionAlgorithm.IsDone())
	{
		std::cerr << "Error: The intersection algorithm failed." << std::endl;
		return TopoDS_Shape();
	}

	// intersectionAlgorithm.Shape() 返回交集的结果，这通常是一个面(Face)、
	// 线(Wire/Edge)、点(Vertex)或它们的组合(Compound)。
	return intersectionAlgorithm.Shape();
}

TopoDS_Shape createHelicalSolid(const TopoDS_Shape& aProfile, const gp_Pnt& aCenter, const gp_Dir& aDirection, const bool bRightDirection, 
	const Standard_Real aPitch, const Standard_Real aTurns, const Standard_Real aRadiusChangePerTurn, const Standard_Real aStartRadius)
{
	// --- 步骤 1: 通过插值法创建螺旋轨迹线 (Wire) ---

	// 1.1 定义螺旋的坐标系
	gp_Ax3 axisSystem(aCenter, aDirection);
	gp_Trsf transformation;
	transformation.SetTransformation(gp::XOY(), axisSystem);

	// 1.2 计算一系列路径点
	// 点的数量决定了曲线的平滑度。每圈36个点通常足够。
	const int pointsPerTurn = 36;
	const int totalPoints = static_cast<int>(aTurns * pointsPerTurn) + 1;

	if (totalPoints < 2) {
		// 点数不足，无法创建曲线
		return TopoDS_Shape();
	}

	Handle(TColgp_HArray1OfPnt) points = new TColgp_HArray1OfPnt(1, totalPoints);
	const double totalAngle = aTurns * 2 * M_PI;

	for (int i = 1; i <= totalPoints; ++i)
	{
		const double currentFraction = (double)(i - 1) / (double)(totalPoints - 1);

		// 计算当前角度
		double currentAngle = currentFraction * totalAngle;
		if (!bRightDirection) {
			currentAngle = -currentAngle;
		}

		// 计算当前圈数
		const double currentTurnCount = currentFraction * aTurns;

		// 计算当前半径
		const double currentRadius = aStartRadius + currentTurnCount * aRadiusChangePerTurn;

		// 计算当前高度
		const double currentHeight = currentTurnCount * aPitch;

		// 在局部坐标系 (以Z轴为中心) 中计算3D点
		gp_Pnt localPnt(currentRadius * cos(currentAngle),
			currentRadius * sin(currentAngle),
			currentHeight);

		// 将局部坐标点转换到最终的世界坐标系
		gp_Pnt globalPnt = localPnt.Transformed(transformation);

		points->SetValue(i, globalPnt);
	}

	// 1.3 使用插值算法通过这些点创建B样条曲线
	GeomAPI_Interpolate interpolator(points, Standard_False, 1.0e-6);
	interpolator.Perform();

	if (!interpolator.IsDone()) {
		// 插值失败
		return TopoDS_Shape();
	}

	Handle(Geom_BSplineCurve) pathCurve = interpolator.Curve();
	TopoDS_Edge pathEdge = BRepBuilderAPI_MakeEdge(pathCurve);
	TopoDS_Wire pathWire = BRepBuilderAPI_MakeWire(pathEdge);


	// --- 步骤 2: 沿着轨迹扫掠轮廓 ---
	BRepOffsetAPI_MakePipe pipeSweeper(pathWire, aProfile);
	pipeSweeper.Build();

	if (pipeSweeper.IsDone()) {
		return pipeSweeper.Shape();
	}

	// 如果失败，返回空Shape
	return TopoDS_Shape();
}

// 这是上述函数的测试代码:

void testCreateHelicalSolid()
{
	// 1. 创建一个轮廓 (例如，一个半径为5的圆形Face)
	gp_Pnt profileCenter(5, 0, 0); // 将轮廓放在X轴上，作为起始点
	gp_Dir profileNormal(0, 1, 0);  // 轮廓的法线方向
	gp_Ax2 profileAxis(profileCenter, profileNormal);
	gp_Circ circle(profileAxis, 1);
	TopoDS_Wire profileWire = BRepBuilderAPI_MakeWire(BRepBuilderAPI_MakeEdge(circle));
	TopoDS_Face profileFace = BRepBuilderAPI_MakeFace(profileWire);

	// 2. 定义螺旋参数
	gp_Pnt center(0, 0, 0);                 // 螺旋中心在原点
	gp_Dir direction(0, 0, 1);              // 沿Z轴正方向上升
	bool bRight = true;     // 右手螺旋
	Standard_Real pitch = 0;				// 每圈上升个单位
	Standard_Real turns = 3;				// 共3圈
	Standard_Real radiusChange = 2.0;       // 每圈半径增加2个单位
	Standard_Real startRadius = 5;			// 起始半径为5

	// 注意：为了让轮廓的初始位置与螺旋线起点对齐，
	// 我们需要更新一下轮廓的位置。
	// 螺旋线的起点位于 (startRadius, 0, 0)
	profileAxis.SetLocation(gp_Pnt(startRadius, 0, 0));
	circle.SetAxis(profileAxis.Axis());
	profileWire = BRepBuilderAPI_MakeWire(BRepBuilderAPI_MakeEdge(circle));
	profileFace = BRepBuilderAPI_MakeFace(profileWire);


	// 3. 调用函数创建实体
	TopoDS_Shape helicalSolid = createHelicalSolid(
		profileFace,
		center,
		direction,
		bRight,
		pitch,
		turns,
		radiusChange,
		startRadius
	);

	//m_mainWindow->createBasicUnitActor(helicalSolid, true);
}